package fr.norsys.mapper.console.service;

import java.util.Iterator;
import java.util.Collection;

import org.apache.commons.beanutils.BeanUtils;

import fr.norsys.mapper.console.model.Variable;
import fr.norsys.mapper.console.utils.UIDGenerator;

public class VariableServiceImpl implements VariableService {

	/**
	 * Add a new variable or edit an already existing one Returns the statement
	 * "The name of the variable is already used"
	 * 
	 * @param variable
	 * @param variables
	 * @return boolean
	 */
	public boolean save(Variable variable, Collection variables) {
		boolean result = false;
		if (nameAlreadyInUse(variable.getId(), variable.getName(), variables)) {
			result = true;
		} else if (variable.getId().equals("")) {
			add(variable, variables);
		} else {
			modify(variable, variables);
		}
		return result;
	}

	/**
	 * Add a new variable
	 * 
	 * @param variable
	 * @param variables
	 * @return
	 */
	private void add(Variable variable, Collection variables) {
		Variable v = null;
		try {
			v = (Variable) BeanUtils.cloneBean(variable);
		} catch (Exception e) {
		}
		v.setId(UIDGenerator.generateId());
		variables.add(v);
	}

	/**
	 * Modify a variable
	 * 
	 * @param variable
	 * @param variables
	 * @return
	 */
	private void modify(Variable var, Collection variables) {
		Variable variable = var;
		for (Iterator it = variables.iterator(); it.hasNext();) {
			Variable c = (Variable) it.next();
			if (variable.getId().equals(c.getId())) {
				fr.norsys.mapper.console.utils.BeanUtils.copyFilledProperties(
						c, variable);
				variable = c;
				break;
			}
		}
	}

	/**
	 * Delete a variable in the variable list using its id
	 * 
	 * @param id
	 * @param variables
	 * @return
	 */
	public void delete(String id, Collection variables) {
		for (Iterator it = variables.iterator(); it.hasNext();) {
			Variable v = (Variable) it.next();
			if (v.getId().equals(id)) {
				variables.remove(v);
				break;
			}
		}
	}

	/**
	 * Look for a variable in the variable list using its id, and return this
	 * variable
	 * 
	 * @param id
	 * @param variables
	 * @return Variable
	 */
	public Variable get(String id, Collection variables) {
		Variable result = null;
		for (Iterator it = variables.iterator(); it.hasNext();) {
			Variable c = (Variable) it.next();
			if (c.getId().equals(id)) {
				result = c;
			}
		}
		return result;
	}

	/**
	 * Look for a variable in the variable list which has the same name as the
	 * param name
	 * 
	 * @param name
	 * @param variables
	 * @return boolean
	 */
	public boolean nameAlreadyInUse(String id, String name, Collection variables) {
		boolean result = false;
		for (Iterator it = variables.iterator(); it.hasNext();) {
			Variable v = (Variable) it.next();
			if (v.getName().equals(name) && !v.getId().equals(id)) {
				result = true;
			}
		}
		return result;
	}
}
